package gitlab

import (
	"project-info/src/handle/response"
	"project-info/src/lib"
	"project-info/src/model"
	"gorm.io/gorm"
)

type GitlabRepoSearchReq struct {
	Text string `json:"text"`
}

type GitlabRepoSearchRes struct {
	ProjectId      int    `json:"project_id"`
	ProjectName    string `json:"project_name"`
	ProjectHttpUrl string `json:"project_http_url"`
}

func SyncGitlabRepos(c *lib.GinContext) error {
	projects, err := lib.GetAllProjects(model.C.General.GitlabToken, model.C.General.GitlabApiUrl)
	if err != nil {
		c.Logger().Error("获取gitlab项目列表失败: " + err.Error())
		return response.JsonFail(c, "获取gitlab项目列表失败")
	}

	for _, project := range projects {
		var oldGitlabRepo model.GitlabRepo
		result := model.DB().Model(&model.GitlabRepo{}).Where("project_id = ?", project.ProjectId).First(&oldGitlabRepo)
		if result.Error != nil && result.Error != gorm.ErrRecordNotFound {
			c.Logger().Error("查询gitlab项目失败: " + result.Error.Error())
			return response.JsonFail(c, "查询gitlab项目失败")
		}

		if oldGitlabRepo.Id == 0 {
			newGitlabRepo := &model.GitlabRepo{
				ProjectId:      project.ProjectId,
				ProjectName:    project.Name,
				ProjectHttpUrl: project.HttpUrl,
				ProjectSshUrl:  project.SshUrl,
				NameSpace:      project.NameSpace,
			}
			result := model.DB().Create(newGitlabRepo)
			if result.Error != nil {
				c.Logger().Error("创建gitlab项目失败: " + result.Error.Error())
				return response.JsonFail(c, "创建gitlab项目失败")
			}
		} else {
			//如果项目信息没有变化，则不更新
			if oldGitlabRepo.ProjectId == project.ProjectId && oldGitlabRepo.ProjectName == project.Name && oldGitlabRepo.ProjectHttpUrl == project.HttpUrl && oldGitlabRepo.ProjectSshUrl == project.SshUrl {
				continue
			}

			oldGitlabRepo.ProjectId = project.ProjectId
			oldGitlabRepo.ProjectName = project.Name
			oldGitlabRepo.ProjectHttpUrl = project.HttpUrl
			oldGitlabRepo.ProjectSshUrl = project.SshUrl
			result := model.DB().Save(oldGitlabRepo)
			if result.Error != nil {
				c.Logger().Error("更新gitlab项目失败: " + result.Error.Error())
				return response.JsonFail(c, "更新gitlab项目失败")
			}
		}
	}

	return response.JsonOk(c, nil, "success")
}

// SearchGitlabRepos 搜索gitlab项目
func SearchGitlabRepos(c *lib.GinContext) error {
	var req *GitlabRepoSearchReq
	if err := c.Bind(&req); err != nil {
		c.Logger().Error(err.Error())
		return response.JsonFail(c, "参数解析错误")
	}

	var repos []*model.GitlabRepo
	result := model.DB().Where("project_http_url like ?", "%"+req.Text+"%").Find(&repos)
	if result.Error != nil && result.Error != gorm.ErrRecordNotFound {
		c.Logger().Error("查询gitlab项目失败: " + result.Error.Error())
		return response.JsonFail(c, "查询gitlab项目失败")
	}

	var res []*GitlabRepoSearchRes
	for _, repo := range repos {
		res = append(res, &GitlabRepoSearchRes{
			ProjectId:      repo.ProjectId,
			ProjectName:    repo.ProjectName,
			ProjectHttpUrl: repo.ProjectHttpUrl,
		})
	}
	return response.JsonOk(c, res, "success")
}
